package Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import common.Base64Helper;
import common.Promotion;
import common.PromotionImage;
import common.Store;
import common.StoreType;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import config.config;
import config.column_name_define;

import android.util.Config;
import android.util.Log;

public class Post {
	
	public static String postRecive(/*String endpoint, */Map<String, String> params)
            throws IOException {   	
        
        URL url;
        String endpoint = "";
        if(config.getDataServer_v1 == true){
        	endpoint = config.SERVER_URL_POST_v1;
        }else{
        	endpoint = config.SERVER_URL_POST;
        }
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        //Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        String result="";
        try {
        	Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            try{
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            }catch(Exception ex){
            	System.out.println("er: " + ex.toString());
            }
            // handle the response
            int status = conn.getResponseCode();
            String re = conn.getResponseMessage();
            BufferedReader rd = null;           
            String line;
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
            while ((line = rd.readLine()) != null) { 
            	result += line ; 
             } 
           
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
            conn.disconnect();
            return result;
            
        } finally {
            if (conn != null) {
                conn.disconnect();
                return result;
            }
        }
      }
	
	public static String postRecive(String endpoint, Map<String, String> params)
            throws IOException {   	
        
        URL url;       
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        //Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        String result="";
        try {
        	Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            try{
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            }catch(Exception ex){
            	System.out.println("er: " + ex.toString());
            }
            // handle the response
            int status = conn.getResponseCode();
            String re = conn.getResponseMessage();
            BufferedReader rd = null;           
            String line;
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
            while ((line = rd.readLine()) != null) { 
            	result += line ; 
             } 
           
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
            conn.disconnect();
            return result;
            
        } finally {
            if (conn != null) {
                conn.disconnect();
                return result;
            }
        }
      }
	
	public static JSONObject postReciveJson(String endpoint, Map<String, String> params)
            throws IOException {   	
        
        URL url;    
        JSONObject jsonObj = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        //Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        String json="";
        try {
        	Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            try{
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            }catch(Exception ex){
            	System.out.println("er: " + ex.toString());
            }
            // handle the response
            int status = conn.getResponseCode();
            String re = conn.getResponseMessage();
            BufferedReader rd = null;           
            String line = null;
            StringBuilder sb = new StringBuilder();
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));            
            String ss = "";
            while ((line = rd.readLine()) != null) { 
            	//sb.append(line + "\n"); 
            	 ss = Base64Helper.B64Decode(line);
             } 
            if(ss.equals("false")){
            	return null;
            }
            StringBuilder sbs = new StringBuilder(ss);
            //json = sb.toString();
            json = sbs.toString();
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
            
            try {
    			jsonObj = new JSONObject(json);
    		} catch (JSONException e) {
    			Log.e("JSON Parser", "Error parsing data " + e.toString());
    		}
            conn.disconnect();
            return jsonObj;
            
        } finally {
            if (conn != null) {
                conn.disconnect();
                return jsonObj;
            }
        }
      }
	
	public static ArrayList<Store> parseJSONStore(JSONObject json){
		ArrayList<Store> resultData = new ArrayList<Store>();
		JSONArray listStore;
		try {
			listStore = json.getJSONArray("stores");
			for(int i = 0 ; i < listStore.length() ; i++){
				JSONObject item = listStore.getJSONObject(i);
				//int id, String name, int type,String type_name, String phone,String mobile, String lat, String lng, String alt, 
				//int province, String province_name, int location_id, String district_name ,String ward, String street, String house_number, 
				//int vote, String description, int customer_id, int chain_store_id,
				//String address,String image,String chain_store_name)
				resultData.add(new Store(Integer.valueOf(item.getString(column_name_define.STORE_ID)),
										 item.getString(column_name_define.STORE_NAME), 
										 Integer.valueOf(item.getString(column_name_define.STORE_TYPE)), 
										 item.getString(column_name_define.STORE_TYPE_NAME_S),
										 item.getString(column_name_define.STORE_PHONE), 
										 item.getString(column_name_define.STORE_MOBILE),
										 item.getString(column_name_define.STORE_LATITUDE), 
										 item.getString(column_name_define.STORE_LONGITUDE), 
										 item.getString(column_name_define.STORE_ALTITUDE), 
										 Integer.valueOf(item.getString(column_name_define.STORE_PROVINCE_ID)), 
										 item.getString(column_name_define.STORE_PROVINCE_NAME), 
										 Integer.valueOf(item.getString(column_name_define.STORE_DISTRICT_ID)), 
										 item.getString(column_name_define.STORE_DISTRICT_NAME), 
										 item.getString(column_name_define.STORE_WARD), 
										 item.getString(column_name_define.STORE_STREET), 
										 item.getString(column_name_define.STORE_HOUSE_NUMBER), 
										 Integer.valueOf(item.getString(column_name_define.STORE_VOTE)), 
										 item.getString(column_name_define.STORE_DESCRIPTION), 
										 Integer.valueOf(item.getString(column_name_define.STORE_CUSTOMER_ID)), 
										 Integer.valueOf(item.getString(column_name_define.STORE_CHAIN_STORE_ID)),
										 item.getString(column_name_define.STORE_HOUSE_NUMBER) 
										 + ", " + item.getString(column_name_define.STORE_STREET)
										 + ", " + item.getString(column_name_define.STORE_WARD)
										 + ", " + item.getString(column_name_define.STORE_DISTRICT_NAME)
										 + ", " + item.getString(column_name_define.STORE_PROVINCE_NAME),
										 config.SERVER_URL_IMAGE+(item.getString(column_name_define.STORE_IMAGE)), 
										 item.getString(column_name_define.STORE_CHAIN_STORE_NAME) 
										)
							);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultData;
	}
	
	
	public static ArrayList<Promotion> parseJSONPromotion(JSONObject json){
		ArrayList<Promotion> resultData = new ArrayList<Promotion>();
		JSONArray listPromotion;
		try {
			listPromotion = json.getJSONArray("promotions");
			for(int i = 0 ; i < listPromotion.length() ; i++){
				JSONObject item = listPromotion.getJSONObject(i);
				Promotion p =  new Promotion(Integer.valueOf(item.getString(column_name_define.PROMOTION_ID)),
						 item.getString(column_name_define.PROMOTION_NAME), 
						 Integer.valueOf(item.getString(column_name_define.PROMOTION_STORE_ID)), 
						 item.getString(column_name_define.PROMOTION_OLD_PRICE), 
						 item.getString(column_name_define.PROMOTION_DECREASE_PRICE), 
						 item.getString(column_name_define.PROMOTION_PERCENT), 
						 Integer.valueOf(item.getString(column_name_define.PROMOTION_FROM_DATE)), 
						 Integer.valueOf(item.getString(column_name_define.PROMOTION_TO_DATE)), 
						 Integer.valueOf(item.getString(column_name_define.PROMOTION_QUANTITY)), 
						 item.getString(column_name_define.PROMOTION_DESCRIPTION),
						 item.getString(column_name_define.PROMOTION_IMAGE),
						 item.getString(column_name_define.PROMOTION_STORE_INFO)
						);
				String storeInfo = p.getStoreInfo(); 
				if(!storeInfo.equals("")){ 
					p.SetStoreByString(storeInfo); 
				}
				p.SetListImagePromotion(p.getImage());
		
				resultData.add(p);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultData;
	}	
	public static ArrayList<StoreType> parseJSONStoreType(JSONObject json){
		ArrayList<StoreType> resultData = new ArrayList<StoreType>();
		JSONArray listStoreType;
		try {
			listStoreType = json.getJSONArray("storetype");
			for(int i = 0 ; i < listStoreType.length() ; i++){
				JSONObject item = listStoreType.getJSONObject(i);
				StoreType p =  new StoreType(Integer.valueOf(item.getString(column_name_define.STORE_TYPE_ID)),
						 item.getString(column_name_define.STORE_TYPE_NAME)
						);				
				resultData.add(p); 
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block 
			e.printStackTrace();
		}
		
		return resultData;
	}
	
	public static JSONObject ParseString2JsonObject(String data){
		
		try{
		JSONObject jsonObj = null;
		String ss = Base64Helper.B64Decode(data);
		StringBuilder sbs = new StringBuilder(ss);
         //json = sb.toString();
         String json = sbs.toString();
        
 		jsonObj = new JSONObject(json);
 		return jsonObj;
		}catch(Exception ex){
			return null;
		}		
	}
}
